import 'dart:convert';
import 'dart:typed_data';

import 'lib_bt_platform_interface.dart';
import 'listener/OnBleConnectListener.dart';
import 'listener/OnBleDataListener.dart';
import 'listener/OnBleScanListener.dart';
import 'listener/OnOtaListener.dart';

class LibBt {
  LibBtPlatform get _libBtPlatform => LibBtPlatform.instance;

  ///设置蓝牙扫描回调
  void setOnBleScanListener(OnBleScanListener listener) {
    _libBtPlatform.setOnBleScanListener(listener);
  }

  ///设置蓝牙连接回调
  void setOnBleConnectListener(OnBleConnectListener listener) {
    _libBtPlatform.setOnBleConnectListener(listener);
  }

  ///设置数据监听回调
  void setOnBleDataListener(OnBleDataListener listener) {
    _libBtPlatform.setOnBleDataListener(listener);
  }

  ///设置ota回调
  void setOnOtaListener(OnOtaListener listener) {
    _libBtPlatform.setOnOtaListener(listener);
  }

  Future<String?> getPlatformVersion() {
    return _libBtPlatform.getPlatformVersion();
  }

  /// 开始扫描
  /// @param scanTime 扫描时长，单位毫秒
  Future<void> startScan(int scanTime) async {
    return _libBtPlatform.invokeMethod<void>("startScan", {"timeout": scanTime});
  }

  /// 停止扫描
  Future<void> stopScan() async {
    return _libBtPlatform.invokeMethod<void>("stopScan");
  }

  /// 连接蓝牙
  /// @param address 蓝牙mac地址
  Future<void> connect(String address) async {
    return _libBtPlatform.invokeMethod<void>("connect", address);
  }

  /// 断开蓝牙
  /// @param address 蓝牙mac地址
  Future<void> disconnect(String address) async {
    return _libBtPlatform.invokeMethod<void>("disconnect", address);
  }

  /// 打开GPS
  Future<void> openGps() async {
    return _libBtPlatform.invokeMethod<void>("openGps");
  }

  /// 打开蓝牙
  Future<void> openBle() async {
    return _libBtPlatform.invokeMethod<void>("openBle");
  }

  /// 蓝牙是否打开
  Future<bool?> isBleEnable() async {
    var ret = await _libBtPlatform.invokeMethod("isBleEnable");
    bool flag = false;
    flag = ret?["isBleEnable"];
    return flag;
  }

  /// GPS是否打开
  Future<bool?> isGpsEnable() async {
    var ret = await _libBtPlatform.invokeMethod("isGpsEnable");
    bool flag = false;
    flag = ret?["isGpsEnable"];
    return flag;
  }

  ///设置UUID信息
  void setUUIDInfo(String uuidJson) {
    _libBtPlatform.invokeMethod("setUUIDInfo", jsonDecode(uuidJson));
  }

  ///开始ota升级
  void startOta(String address, Uint8List data) {
    _libBtPlatform.invokeMethod("startOta", {"address": address, "data": base64Encode(data)});
  }

  ///是否是正在升级
  Future<bool> isOTA() async {
    var flag = await _libBtPlatform.invokeMethod<bool>("isOTA");
    return flag ?? false;
  }

  ///发送数据给设备
  void write(String address, String serviceUuid, String uuid, List<int> data) {
    _libBtPlatform.invokeMethod("write", {
      "address": address,
      "serviceUuid": serviceUuid,
      "uuid": uuid,
      "data": base64Encode(data),
    });
  }
}
